﻿using Azure;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.CJL.API.Application.Command.ProcessCommand;
using System.CJL.Domain;
using System.CJL.Domain.DTO;
using System.CJL.Infrstructre.Interface;

namespace System.CJL.API.Application.CommandHanlder.ProcessCommandHanler
{
    public class ProcessShowCommandHandler : IRequestHandler<ProcessShowCommand, PageDTO<Process>>
    {
        IProcessRepository _repository;
        public ProcessShowCommandHandler(IProcessRepository repository)
        {
            _repository=repository;
        }

        public async Task<PageDTO<Process>> Handle(ProcessShowCommand request, CancellationToken cancellationToken)
        {
            var list =  (await _repository.GetAll()).Where(x=>!x.IsDelete);
            if (!string.IsNullOrEmpty(request.ProcessNumebring))
            {
                list = list.Where(x => x.ProcessNumebring.Contains(request.ProcessNumebring)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProcessName))
            {
                list = list.Where(x => x.ProcessName.Contains(request.ProcessName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProcessStatus))
            {
                list = list.Where(x => x.ProcessStatus == request.ProcessStatus).ToList();
            }
            PageDTO<Process> result = new PageDTO<Process>();
            result.listcount= list.Count();
            result.pagecount= (int)Math.Ceiling(list.Count()*1.0/request.PageSize);
            result.plist = list.OrderByDescending(x => x.AddTime).Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList();
            return result;
        }
    }
}
